<template>
  <div class="app-container-flex">
    <NewFullScreen
      v-model="showDialog"
      :title="title"
      :btn-list="fullInfo.btnList"
    >
      <div class="model-panel">
        <div class="model-panel-title">
          <p>{{ $t('basic_information') }}</p>
        </div>
        <div class="model-panel-body">
          <basic-information :info="infoList"></basic-information>
          <PageForm
            v-model:ref-obj="formInfo.ref"
            :disabled="formInfo.disabled"
            :data="formInfo.data"
            :field-list="formInfo.fieldList"
            :rules="formInfo.rules"
            :label-width="formInfo.labelWidth"
          >
          </PageForm>
        </div>
      </div>

      <div class="model-panel">
        <div class="model-panel-title">
          <Tooltip :text="$t('detailInfo')" />
        </div>
        <div class="model-panel-body">
          <!-- 条件栏 -->
          <NewPageFilter
            v-model:query="filterInfo.query"
            :filter-btn="filterInfo.list"
          >
            <template v-slot:filter-removeProduct>
              <el-button :disabled="!canDeleteProduct" @click="removeProduct"
                >删除产品</el-button
              >
            </template>
            <template v-slot:filter-smartRecommendation>
              <el-button @click="_smartRecommendation">智能推荐</el-button>
            </template>
            <template v-slot:filter-receivingCodeScan>
              <ScanInputBox
                :query="scanInfo.query"
                :api="scanInfo.api"
                @callback="onCallBackScanData"
              />
            </template>
          </NewPageFilter>
          <div class="flex_full_item">
            <el-form ref="tableForm" :model="tableInfo" style="width: 100%">
              <!-- 表格 -->
              <page-table
                :refresh="tableInfo.refresh"
                :init-curpage="tableInfo.initCurpage"
                v-model:data="tableInfo.data"
                :pager="false"
                :summary="true"
                :summary-field-list="tableInfo.summaryFieldList"
                :tab-index="true"
                :field-list="tableInfo.fieldList"
                :handle="tableInfo.handle"
                :row-class-name="tableRowClassName"
                @handleEvent="handleEvent"
              >
                <template v-slot:col-qty="scope">
                  <template v-if="!tableInfo.isSysGroup">
                    <el-form-item
                      v-if="
                        scope.row.codeType === 1 || scope.row.codeType === 4
                      "
                      class="margin-bottom"
                    >
                      <div class="page-table-input-number-wrapper">
                        <div class="page-table-input-number-left">
                          <div class="page-table-input-number-item">
                            <el-form-item
                              :prop="`data.${scope.$index}.largeUnitQty`"
                              :rules="
                                scope.$index >= 0
                                  ? [
                                      {
                                        validator: $validate.positiveAndZero,
                                        trigger: 'blur',
                                      },
                                    ]
                                  : []
                              "
                            >
                              <el-input-number
                                v-model.lazy="scope.row.largeUnitQty"
                                style="width: 100%; margintop: 18px"
                                clearable
                                controls-position="right"
                                :precision="
                                  scope.row.qtyOperateMode === 0 ||
                                  scope.row.qtyOperateMode === 2
                                    ? 0
                                    : systemConfig.qty_show_precision
                                "
                                :min="0"
                                :max="largeMax(scope.row)"
                                @change="
                                  changeLarge(
                                    $event,
                                    scope.row,
                                    `data.${scope.$index}.largeUnitQty`
                                  )
                                "
                              />
                            </el-form-item>
                            <div class="page-table-input-number-item-unite">
                              {{ scope.row.unitName }}
                            </div>
                          </div>
                          <div
                            v-if="
                              scope.row.unitConvertCoefficient > 1 &&
                              scope.row.qtyOperateMode === 2
                            "
                            class="page-table-input-number-item"
                          >
                            <el-form-item>
                              <el-input-number
                                v-model.lazy="scope.row.smallUnitQty"
                                style="width: 100%; margintop: 18px"
                                clearable
                                controls-position="right"
                                :precision="0"
                                :min="0"
                                :max="smallMax(scope.row)"
                              />
                            </el-form-item>
                            <div class="page-table-input-number-item-unite">
                              {{ scope.row.calcUnitName }}
                            </div>
                          </div>
                        </div>
                        <div
                          v-if="scope.row.qtyOperateMode === 2"
                          class="page-table-input-number-right"
                        >
                          {{ $fn.qtyFormatter(scope.row.qty) }}
                        </div>
                      </div>
                    </el-form-item>
                    <span
                      v-else-if="
                        scope.row.codeType === 2 || scope.row.codeType === 3
                      "
                      >{{ $fn.qtyFormatter(scope.row.qty) }}</span
                    >
                  </template>
                  <span v-else>{{ $fn.qtyFormatter(scope.row.qty) }}</span>
                </template>
              </page-table>
            </el-form>
          </div>
        </div>
      </div>
    </NewFullScreen>
    <!-- 选择产品 -->
    <select-detail-depot-storage
      v-if="selectDepotStorageInfo.visible"
      v-model:show-dialog="selectDepotStorageInfo.visible"
      :query="selectDepotStorageInfo.query"
      :order-id="id"
      :exclude-product-ids="selectDepotStorageInfo.excludeProductIds"
      :exclude-query-list="selectDepotStorageInfo.excludeQueryList"
      :left-table-key="selectDepotStorageInfo.leftTableKey"
      :right-table-key="selectDepotStorageInfo.rightTableKey"
      :depot-id="infoList.data.exportDepotId"
      :show-price="$permission('useAudit:price')"
      @callback="selectDepotStorageCallBack"
    />
    <!-- 个体操作 -->
    <select-individual
      v-if="individualInfo.visible"
      v-model:visible="individualInfo.visible"
      v-model:left-query-obj="individualInfo.leftQuery"
      v-model:right-query-obj="individualInfo.rightQuery"
      v-model:info-list="individualInfo.productInfo"
      :request-right-list="!!id"
      v-model:right-api="individualInfo.rightApi"
      v-model:left-api="individualInfo.leftApi"
      v-model:right-vo="individualInfo.rightVo"
      :left-table-key="individualInfo.leftTableKey"
      :show-price="$permission('useAudit:price')"
      :scan-info="scanInfo"
      @callbackSacn="callbackSacn"
      @callback="selectedProductDetails"
    />
  </div>
</template>

<script setup name="useApplicationExport">
import PageTable from '@/components/PageTable/index'

import SelectDetailDepotStorage from './selectDetailDepotStorage/selectDetailDepotStorage'

import {
  getUseTemplatePage,
  getUseApplication,
  createUseExport,
  exportUseApplication,
  printUseApplication,
  smartRecommendation,
  getUseApplicationDetail,
} from '@/api/use'
import {
  depotStockCustomizeScan,
  otherExportOrderDetailsCustomizeListAll,
  getDepotStockCustomizeListPage,
  depotStockValidateOptimalValidate,
} from '@/api/stock'
import BasicInformation from '@/components/BasicInformation/index'
import selectIndividual from '../components/individual'
import ScanInputBox from '@/views/stock/components/ScanInputBox'
import { getCoreSystemConfigAll } from '@/api/core'
import { getCustomizeSetting } from '@/api/customize'
import moment from 'moment'
import _ from 'lodash'
import {
  setDisableTime,
  _getCurrentFiscalPeriod,
} from '@/common/js/dateOperation'
const { proxy } = getCurrentInstance()
const emit = defineEmits()

const Tooltip = defineAsyncComponent(() => import('@/components/Tooltip/index'))
const props = defineProps(['visible', 'title', 'id'])

const systemConfig = ref(proxy.$store.state.permission.systemConfig)
const index = ref('')
const productIds = ref([])
const selectRows = ref([])
const storageData = ref([])
const chooseIndex = ref([])
const totalRows = ref([])
const tableData = ref([])
const formRefs = ref()
const applicationDetailProductIds = ref('')
const selectDepotStorageInfo = reactive({
  //库存产品
  visible: false,
  excludeProductIds: [],
  excludeQueryList: [], //库存产品左侧过滤配置
  query: {
    productId: { queryType: 'IN', queryCategory: 'AND', value: '' },
    depotId: { queryType: 'IN', queryCategory: 'AND', value: '' },
    isConsignBusiness: {
      queryType: 'EQUALS',
      queryCategory: 'AND',
      value: '',
    },
  },
  leftTableKey:
    'useApplicationOrderRatifyModifyBatchNumber-com.slip.spd.entity.vo.stock.DepotStockVO',
  rightTableKey:
    'useApplicationOrderRatifyModifySingle-com.slip.spd.entity.vo.stock.DepotStockVO',
})
const scanInfo = reactive({
  api: depotStockCustomizeScan,
  query: {
    queryMap: {
      isConsignBusiness: {
        queryType: 'EQUALS',
        queryCategory: 'AND',
        value: '',
      },
    },
    customizeUserVO: {},
    queryParams: {
      depotId: '',
      // validateExpire: false
    },
  },
})
const infoList = reactive({
  ref: null,
  data: {},
  fieldList: [
    { label: '申请单号', value: 'orderNo', type: 'text' },
    { label: '领用人', value: 'createUserName', type: 'text' },
    { label: '领用部门', value: 'deptName', type: 'text' },
    { label: '领入仓库', value: 'depotName', type: 'text' },
    { label: '领出仓库', value: 'exportDepotName', type: 'text' },
    {
      label: '是否寄售业务',
      value: 'isConsignBusinessValue',
      type: 'text',
      show:
        props.id &&
        proxy.$store.state.permission.systemConfig.is_consign_business == 1,
    },
  ],
})
const formInfo = ref({
  ref: null,
  data: {},
  fieldList: [
    {
      label: '业务日期',
      value: 'businessDate',
      type: 'date',
      clearable: false,
    },
  ],
  rules: {
    businessDate: [
      { required: true, message: '请选择业务日期', target: 'blur' },
    ],
  },
  labelWidth: '150px',
})
// 过滤相关配置
const filterInfo = reactive({
  query: {
    customizeUserVO: {},
    queryMap: {
      orderId: {
        queryType: 'EQUALS',
        queryCategory: 'AND',
        value: null,
      },
    },
  },
  list: [
    { type: 'button', label: '添加产品', event: addProduct },
    { type: 'slot', value: 'removeProduct' },
    { type: 'slot', value: 'smartRecommendation' },
    { type: 'slot', value: 'receivingCodeScan' },
  ],
})
const detailFilterInfo = ref({
  query: {
    customizeUserVO: {},
    queryMap: {
      orderId: {
        queryType: 'EQUALS',
        queryCategory: 'AND',
        value: props.id,
      },
    },
    queryParams: {},
  },
  searchList: [],
})

// 表格相关
const tableInfo = reactive({
  refresh: 1,
  initCurpage: 1,
  data: [],
  map: new Map(),
  isSysGroup: true, //新增修改页是否有后端合并
  sysGroup: [], //新增修改页后端合并项
  selections: [],
  summaryFieldList: [
    { value: 'qty', formatter: proxy.$fn.qtyFormatter },
    { value: 'price', show: 'false' },
    { value: 'sumAmount', formatter: proxy.$fn.TripartiteMethod },
  ],
  fieldList: [],
  handle: {
    fixed: 'right',
    label: '操作',
    width: '120',
    btList: [
      {
        label: '选择个体',
        event: _selectIndividual,
        ifRender: ifRenderValue,
        show: true,
      },
      {
        label: '删除',
        event: removeProduct,
        show: true,
        popconfirmText: '删除后将改变数据,是否继续？',
      },
    ],
  },
})
const fullInfo = reactive({
  btnList: [
    { label: '提交', event: _export, show: true },
    { label: '导出excel', event: exportExcel, show: false },
    { label: '打印', event: print, show: false },
  ],
})
//选择产品相关
let productInfo = reactive({
  visible: false,
  tableKey:
    'useApplicationOrderModifyRatifyProduct-com.slip.spd.entity.vo.core.CoreProductVONew',
  query: {
    queryMap: {
      status: {
        queryType: 'IN',
        queryCategory: 'AND',
        value: 1,
      },
      id: {
        queryType: 'NOT_IN',
        queryCategory: 'AND',
        value: '',
      },
      codeType: {
        queryType: 'IN',
        queryCategory: 'AND',
        value: '1,2,4',
      },
      type: {
        asTbName: 'core_product_new',
        columnName: 'type',
        queryResource: 0,
        queryType: 'EQUALS',
        queryCategory: 'AND',
        value: 0,
      },
    },
  },
})
const userInfo = reactive({
  visible: false,
})
const depotInfo = reactive({
  visible: false,
  depotType: '',
  query: {
    idNotIn: '',
    useTypeId: '1',
    status: '1',
  },
})
const sourceDeptInfo = reactive({
  visible: false,
  depotType: '',
  query: {
    idNotIn: '',
    status: '1',
  },
})
const deptInfo = reactive({
  visible: false,
  query: {
    deptAuth: 'id',
    status: '1',
  },
})
const templateInfo = reactive({
  visible: false,
  api: getUseTemplatePage,
  query: {
    deptId: '',
  },
})
//选择库存产品
const depotStorageInfo = reactive({
  currentIndex: null,
})
const batchNumberInfo = reactive({
  api: getDepotStockCustomizeListPage,
  tableKey:
    'useApplicationOrderRatifyModifyBatchNumber-com.slip.spd.entity.vo.stock.DepotStockVO',
  visible: false,
  query: {
    queryMap: {
      status: {
        queryType: 'IN',
        queryCategory: 'AND',
        value: 1,
      },
      id: {
        queryType: 'NOT_IN',
        queryCategory: 'AND',
        value: '',
      },
      codeType: {
        queryType: 'IN',
        queryCategory: 'AND',
        value: '1,2,4',
      },
    },
  },
})
//个体操作相关
const individualInfo = reactive({
  visible: false,
  selectObj: {}, //库存产品弹窗左边后端合并项
  productInfo: {}, //个体操作的当前这条数据
  leftQuery: {}, //个体弹窗左边数据查询条件
  rightQuery: {}, //个体弹窗右边数据查询条件
  rightApi: otherExportOrderDetailsCustomizeListAll, //个体弹窗右边数据接口
  leftApi: getDepotStockCustomizeListPage, //个体弹窗左边数据接口
  rightVo: {}, //个体弹窗右边配置
  leftTableKey:
    'useApplicationOrderModifyRatifyOperate-com.slip.spd.entity.vo.stock.DepotStockVO',
})

const showDialog = computed({
  get() {
    return props.visible
  },
  set(newValue) {
    emit('update:visible', newValue) // 更新父组件visible
  },
})
const canDeleteProduct = computed(() => {
  return tableInfo.selections.length
})

watch(
  () => props.visible,
  (value) => {
    showDialog.value = value
  },
  { immediate: true }
)
watch(
  () => tableInfo.data,
  (val) => {
    if (val.length && !tableInfo.isSysGroup) {
      val.forEach((row) => {
        let smallUnitQty = parseFloat(row.smallUnitQty || 0)
        let unitConvertCoefficient = parseFloat(row.unitConvertCoefficient || 1)
        let largeUnitQty = parseFloat(row.largeUnitQty || 0)
        let calcQty = proxy.$fn.accAdd(
          proxy.$fn.accMul(largeUnitQty, unitConvertCoefficient),
          smallUnitQty
        )
        let qty = proxy.$fn.qtyFormatter(
          proxy.$fn.accDiv(calcQty, unitConvertCoefficient)
        )
        row['calcQty'] = calcQty
        row['qty'] = qty
        row.sumAmount = proxy.$fn.accDiv(
          proxy.$fn.accMul(calcQty, parseFloat(row.price)),
          unitConvertCoefficient
        )
        if (row.details && row.details.length) {
          row.details[0].qty = qty
          row.details[0].calcQty = calcQty
          row.details[0].largeUnitQty = largeUnitQty
          row.details[0].smallUnitQty = smallUnitQty
          row.details[0].sumAmount = row.sumAmount
        }
      })
    }
  },
  { deep: true }
)

let obj = {
  orderNo: {
    label: '单号',
    value: 'orderNo',
    componentType: 'input',
    show: false,
    // type: 'slot',
    hidden: true,
  },
  qty: {
    label: '出库数量',
    value: 'qty',
    type: 'slot',
    componentType: 'number',
    formatter: proxy.$fn.qtyFormatter,
    hidden: true,
  },
  applicationQty: {
    label: '申请数量',
    value: 'applicationQty',
    type: 'column',
    formatter: proxy.$fn.qtyFormatter,
    componentType: 'number',
    hidden: true,
  },
  availableQty: {
    label: '可出库数量',
    value: 'availableQty',
    type: 'column',
    formatter: proxy.$fn.qtyFormatter,
    componentType: 'number',
    hidden: true,
  },
  price: {
    label: '单价',
    value: 'price',
    minWidth: '150px',
    type: 'column',
    formatter: proxy.$fn.TripartiteMethod,
    permission: !proxy.$permission('useAudit:price'),
    hidden: true,
  },
  sumAmount: {
    label: '总金额',
    value: 'sumAmount',
    type: 'column',
    formatter: proxy.$fn.TripartiteMethod,
    permission: !proxy.$permission('useAudit:price'),
    hidden: true,
  },
  defaultSupplierPrice: {
    label: '默认供应商价格',
    value: 'defaultSupplierPrice',
    type: 'column',
    permission: !proxy.$permission('useAudit:price'),
    formatter: proxy.$fn.TripartiteMethod,
    hidden: true,
  },
}
tableInfo.fieldList = Object.values({
  ...proxy.$fn.deepClone(proxy.$fieldfList.FieldList),
  ...proxy.$fn.deepClone(obj),
})
detailFilterInfo.value.searchList = Object.values({
  ...proxy.$fn.deepClone(proxy.$fieldfList.FieldList),
  commonName: {
    label: '通用名称',
    value: 'commonName',
    componentType: 'input',
    show: true,
    hidden: true,
  },
  statusValue: {
    show: false,
    hidden: true,
  },
  deptName: {
    show: false,
    hidden: true,
  },
})

getCustomize()
getDetailsCustomize()
getInvdividualRightCustomize()

let disStartDate = ref('')
let disEndDate = ref('')
setDisableTime(formInfo.value.fieldList, disStartDate, disEndDate)
async function setBusinessDate() {
  formInfo.value.data.businessDate = await _getCurrentFiscalPeriod(
    formInfo.value.fieldList,
    proxy,
    disStartDate,
    disEndDate
  )
}
onMounted(() => {
  formRefs.value = [proxy.$refs['tableForm'], infoList.ref]
  proxy.$nextTick(() => {
    if (!props.id) {
      infoList.fieldList = infoList.fieldList.filter(
        (item) => item.value !== 'orderNo'
      )
    }
  })
})
function getDetailsCustomize() {
  let param = {
    tableKey:
      'useApplicationOrderAuditDetail-com.slip.spd.entity.vo.use.UseApplicationOrderDetailVO',
  }
  getCustomizeSetting(param).then((res) => {
    if (res && res.success) {
      let data = res.data
      detailFilterInfo.value.query.customizeUserVO = res.data

      let searchInfo = proxy.$fn.setSearchList(
        detailFilterInfo.value.searchList,
        data.detail
      )

      detailFilterInfo.value.query.queryMap = {
        ...proxy.$fn.deepClone(detailFilterInfo.value.query.queryMap),
        ...proxy.$fn.deepClone(searchInfo.queryMap),
      }
      detailFilterInfo.value.query.queryParams = {
        ...detailFilterInfo.value.query.queryParams,
      }
      getList()
    }
  })
}

function largeMax(row) {
  if (row.qtyOperateMode === 2) {
    return parseInt(row.stockAvailableCalcQty / row.unitConvertCoefficient)
  } else {
    return row.stockAvailableQty
  }
}
function smallMax(row) {
  let largeUnitQty = parseInt(
    row.stockAvailableCalcQty / row.unitConvertCoefficient
  )
  if (largeUnitQty === 0 || row.largeUnitQty === largeUnitQty) {
    return parseInt(row.stockAvailableCalcQty % row.unitConvertCoefficient)
  } else {
    return row.unitConvertCoefficient - 1
  }
}
function changeLarge(e, row, str) {
  proxy.$refs.tableForm.clearValidate(str)
  let largeUnitQty = parseInt(
    row.stockAvailableCalcQty / row.unitConvertCoefficient
  )
  if (row.qtyOperateMode === 2 && row.unitConvertCoefficient > 1) {
    if (largeUnitQty > 0 && e === largeUnitQty) {
      let smallUnitQty = parseInt(
        row.stockAvailableCalcQty % row.unitConvertCoefficient
      )
      if (row.smallUnitQty > smallUnitQty) {
        row.smallUnitQty = smallUnitQty
      }
    }
  }
}
function tableRowClassName({ row = undefined }) {
  if (row.isChoice) {
    return 'success-row'
  } else {
    return ''
  }
}

function ifRenderValue() {
  return tableInfo.isSysGroup
}
function getList() {
  //修改请求明细信息
  getUseApplicationDetail(detailFilterInfo.value.query).then((resp) => {
    if (resp && resp.success && resp.data.length) {
      //获取产品ID
      let productIds = []
      resp.data.map((item) => {
        //当可出库数量小于等于0的时候，产品不再添加到弹框搜索列表中
        if (item.qty > item.preExportQty) {
          productIds.push(item.productId)
        }
      })
      applicationDetailProductIds.value = String(productIds)
      tableData.value = resp.data
    }
  })
}
function getMain() {
  getUseApplication(props.id).then((resp) => {
    if (resp && resp.success) {
      infoList.data = resp.data
      scanInfo.query.queryParams.depotId = resp.data.exportDepotId
      scanInfo.query.queryMap.isConsignBusiness.value =
        resp.data.isConsignBusiness
      setBusinessDate()
    }
  })
  filterInfo.query.queryMap.orderId.value = props.id ////
}
function getCustomize() {
  let param = {
    tableKey:
      'useApplicationOrderRatifyModify-com.slip.spd.entity.vo.use.UseExportOrderDetailVO',
  }
  tableInfo.isSysGroup = false
  getCustomizeSetting(param).then((res) => {
    if (res && res.success) {
      let data = res.data
      tableInfo.fieldList = proxy.$fn.setFieldList(
        tableInfo.fieldList,
        data.detail
      )
      for (let key in data.detail) {
        if (data.detail[key].sysGroupLevel > 0) {
          tableInfo.isSysGroup = true
        }
      }
      filterInfo.query.customizeUserVO = data
      getDeoptLeftCustomize()
      getMain()
    }
  })
}
// 触发事件
function handleEvent(event, data) {
  switch (event) {
    case 'tableCheck':
      tableInfo.selections = [...data]
      break
  }
}
function addProduct() {
  let keys = [...tableInfo.map.keys()]
  let excludeQueryList = []
  if (keys.length && tableInfo.sysGroup.length) {
    excludeQueryList = keys.map((item) => JSON.parse(item))
  }
  selectDepotStorageInfo.excludeQueryList = excludeQueryList //库存产品左侧过滤配置
  selectDepotStorageInfo.query.isConsignBusiness.value =
    infoList.data.isConsignBusiness
  selectDepotStorageInfo.visible = true
}
async function selectDepotStorageCallBack(rows = []) {
  console.log('1', rows)
  //库存产品返回

  let map = await proxy.$fn.getDepotStorage(
    rows,
    tableInfo.sysGroup,
    tableInfo.map,
    otherExportOrderDetailsCustomizeListAll, //个体弹窗右边数据接口
    props.id,
    individualInfo.rightVo //个体弹窗右边表格配置
  )
  tableInfo.map = map
  tableInfo.data = [...map.values()]
  //根据产品id来给选择的产品赋值申领数量
  tableInfo.data.map((item) => {
    tableData.value.map((el) => {
      if (item.productId === el.productId) {
        item.applicationQty = el.qty
        item.applicationCalcQty = el.calcQty
        item.availableQty = proxy.$fn.Subtr(el.qty, el.preExportQty)
        item.availableCalcQty = proxy.$fn.Subtr(el.calcQty, el.preExportCalcQty)
      }
    })
  })
  selectDepotStorageInfo.excludeProductIds = tableInfo.data.map(
    (item) => item.productId
  )
}
function _export() {
  if (tableInfo.data.length === 0) {
    proxy.$message({
      duration: 3500,
      type: 'warning',
      showClose: true,
      message: '出库明细不能为空',
    })
    return
  } else {
    const qtyZero = tableInfo.data
      .filter((item) => !item.qty || item.qty === 0)
      .map((item) => item.commonName)

    if (qtyZero.length) {
      proxy.$alert(`产品【${qtyZero}】出库数量不能为0`, '操作提示', {
        confirmButtonText: '确定',
      })
      return
    }
    if (systemConfig.value.optimal_validate == 1) {
      let params = tableInfo.data.map((item) => {
        return {
          calcQty: item.calcQty || '',
          depotStockId: item.depotStockId || '',
        }
      })
      depotStockValidateOptimalValidate(params).then((res) => {
        if (res && res.code && res.code == 200) {
          reSave()
        }
      })
    } else {
      reSave()
    }
  }
}
function reSave() {
  let newDatas = {
    storeDeptId: infoList.data.deptId,
    storeDepotId: infoList.data.depotId,
    ...infoList.data,
    mergeDetails: proxy.$fn.filterBlacklist(tableInfo.data),
    ...formInfo.value.data,
  }
  getCoreSystemConfigAll().then((resp) => {
    if (resp && resp.success) {
      let find = resp.data.find(
        (item) => item.systemConfigCode === 'allow_expire_out'
      )
      if (find) {
        let expire = validateExpire(tableInfo.data)
        if (find.value === '1') {
          if (expire) {
            proxy
              .$confirm(expire + ',是否继续?', '警告', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                dangerouslyUseHTMLString: true,
              })
              .then(() => {
                createUseExport(newDatas).then((resp) => {
                  if (resp && resp.success) {
                    showDialog.value = false
                    emit('returnModify')
                  }
                })
                return
              })
              .catch(() => {
                return
              })
          } else {
            createUseExport(newDatas).then((resp) => {
              if (resp && resp.success) {
                showDialog.value = false
                emit('returnModify')
              }
            })
            return
          }
        } else {
          if (expire) {
            proxy.$alert(expire + '，不允许出库！', '操作提示', {
              confirmButtonText: '确定',
              dangerouslyUseHTMLString: true,
            })
            return
          } else {
            createUseExport(newDatas).then((resp) => {
              if (resp && resp.success) {
                showDialog.value = false
                emit('returnModify')
              }
            })
            return
          }
        }
      } else {
        createUseExport(newDatas).then((resp) => {
          if (resp && resp.success) {
            showDialog.value = false
            emit('returnModify')
          }
        })
        return
      }
    }
  })
}
function validateExpire(list = []) {
  let currentDate = moment().format('YYYY-MM-DD')
  let msg = ''
  list.forEach((item, index) => {
    if (item.validityDate && moment(item.validityDate).isBefore(currentDate)) {
      msg = msg + `第【${index + 1}】行产品【${item.commonName}】已过期，<br>`
    }
  })
  return msg
}
async function callbackSacn(data, oldInfo, callback) {
  //个体操作弹窗扫码回调
  let { mergeDetail, detail } = data
  mergeDetail[0].details = [detail]

  let key = []
  tableInfo.sysGroup.forEach((row) => {
    let obj = {}
    obj.columnName = row.columnName
    obj.asTbName = row.asTbName
    obj.value = mergeDetail[0][row.key]
    key.push(obj)
  })
  let newKey = JSON.stringify(key)
  if (tableInfo.map.has(newKey)) {
    if (
      oldInfo.groupConcatDepotStockIds.includes(detail.depotStockId.toString())
    ) {
      callback(true)
      return
    } else {
      if (oldInfo.key === newKey) {
        await setData(mergeDetail, newKey)
        await callback(false)
      } else {
        let value = tableInfo.map.get(newKey)
        if (
          await value.groupConcatDepotStockIds.includes(
            detail.depotStockId.toString()
          )
        ) {
          if ((await proxy.$fn.confirmRes()) === 'confirm') {
            await selectedProductDetails(oldInfo)
            await setData(
              mergeDetail,
              newKey,
              value.details && value.details.length
            )
            await callback(false)
          } else {
            await setData(
              mergeDetail,
              newKey,
              value.details && value.details.length
            )
            await callback(false)
          }
        } else {
          if ((await proxy.$fn.confirmRes()) === 'confirm') {
            await selectedProductDetails(oldInfo)
            await setData(mergeDetail, newKey)
            await callback(false)
          } else {
            await setData(mergeDetail, newKey)
            await callback(false)
          }
        }
      }
    }
  } else {
    if ((await proxy.$fn.confirmRes()) === 'confirm') {
      await selectedProductDetails(oldInfo)
      await setData(mergeDetail, newKey)
      await callback(false)
    } else {
      await setData(mergeDetail, newKey)
      await callback(false)
    }
  }
}
async function _selectIndividual(data) {
  //选择个体
  await getIndividualInfoQuery(data)
  individualInfo.visible = true
}

async function getIndividualInfoQuery(data) {
  // 设置个体操作参数
  console.log(formInfo.value)
  for (let key in individualInfo.selectObj) {
    individualInfo.selectObj[key].value = data[key]
  }
  individualInfo.leftQuery.isConsignBusiness = {
    queryType: 'EQUALS',
    queryCategory: 'AND',
    value: infoList.data.isConsignBusiness,
  }
  individualInfo.rightQuery.isConsignBusiness = {
    queryType: 'EQUALS',
    queryCategory: 'AND',
    value: infoList.data.isConsignBusiness,
  }
  individualInfo.leftQuery.id = {
    queryType: 'NOT_IN',
    queryCategory: 'AND',
    value: data.groupConcatDepotStockIds,
  }
  individualInfo.leftQuery.productId = {
    queryType: 'RIGHT_LIKE',
    queryCategory: 'AND',
    value: data.productId,
  }
  individualInfo.leftQuery.orgId = {
    queryType: 'RIGHT_LIKE',
    queryCategory: 'AND',
    value: tableInfo.data[0].orgId,
  }
  individualInfo.leftQuery.depotId = {
    queryType: 'IN',
    queryCategory: 'AND',
    value: scanInfo.query.queryParams.depotId,
  }
  individualInfo.leftQuery = {
    ...individualInfo.leftQuery,
    ...individualInfo.selectObj,
  }
  individualInfo.rightQuery.id = {
    queryType: 'IN',
    queryCategory: 'AND',
    value: data.groupConcatIds,
  }
  individualInfo.rightQuery.otherExportId = {
    queryType: 'EQUALS',
    queryCategory: 'AND',
    value: props.id,
  }
  individualInfo.productInfo = data
}
async function selectedProductDetails(data) {
  //个体返回
  if (data.details && data.details.length) {
    tableInfo.map.set(data.key, data)
    let index = tableInfo.data.findIndex((item) => item.key === data.key)
    if (index !== -1) {
      tableInfo.data[index] = data
    }
  } else {
    removeProduct(data)
  }
}
async function setData(data, newKey, type = false) {
  //个体操作弹窗扫码回调设置数据

  let newData
  if (!type) {
    let map = await proxy.$fn.getDepotStorage(
      [data],
      tableInfo.sysGroup,
      tableInfo.map,
      otherExportOrderDetailsCustomizeListAll,
      props.id,
      individualInfo.rightVo,
      'scan'
    )
    tableInfo.map = map
    tableInfo.data = [...map.values()]
    newData = map.get(newKey)
  } else {
    newData = tableInfo.map.get(newKey)
  }
  await getIndividualInfoQuery(newData)
}
//删除产品
function removeProduct(row = undefined) {
  if (row && row.key) {
    tableInfo.data = tableInfo.data.filter((item) => item.key !== row.key)
    let key = row.key
    tableInfo.map.delete(key)
  } else {
    proxy
      .$confirm('删除后将改变数据,是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
      .then(() => {
        tableInfo.selections.forEach((row) => {
          for (let [key, value] of tableInfo.map) {
            if (key === row.key) {
              tableInfo.map.delete(key)
            }
          }
        })
        tableInfo.data = tableInfo.data.filter((row) => {
          return !tableInfo.selections.includes(row)
        })
      })
  }
  selectDepotStorageInfo.excludeProductIds = tableInfo.data.map(
    (item) => item.productId
  )
}
//智能推荐
function _smartRecommendation() {
  let params = {
    ...infoList.data,
    mergeDetails: tableInfo.data,
  }
  let sysGroup = tableInfo.sysGroup
  smartRecommendation(params).then((resp) => {
    if (resp && resp.success) {
      let data = resp.data
      if (data && data.length) {
        data.forEach((item) => {
          let key = []
          if (sysGroup.length) {
            sysGroup.forEach((row) => {
              let obj = {}
              obj.columnName = row.columnName
              obj.asTbName = row.asTbName
              obj.value = item[row.key]
              key.push(obj)
            })
          }
          item.key = JSON.stringify(key)
        })
        let groupData = _.groupBy(data, (item) => {
          return item.key
        })
        let groupDataValue = Object.values(groupData)
        let newArr = []
        groupDataValue.forEach((row) => {
          let arr = proxy.$fn.deepClone(row)
          let obj = arr[0]
          let calcQty = 0
          let largeUnitQty = 0
          let smallUnitQty = 0
          let sumAmount = 0
          let stockAvailableCalcQty = 0
          let groupConcatDepotStockIds = []
          arr.forEach((item) => {
            largeUnitQty = proxy.$fn.accAdd(
              largeUnitQty,
              item.largeUnitQty || 0
            )
            smallUnitQty = proxy.$fn.accAdd(
              smallUnitQty,
              item.smallUnitQty || 0
            )
            sumAmount = proxy.$fn.accAdd(sumAmount, item.sumAmount || 0)
            calcQty = proxy.$fn.accAdd(calcQty, item.calcQty || 0)
            stockAvailableCalcQty = proxy.$fn.accAdd(
              stockAvailableCalcQty,
              item.stockAvailableCalcQty || 0
            )
            groupConcatDepotStockIds.push(item.depotStockId)
          })
          obj['largeUnitQty'] = largeUnitQty
          obj['smallUnitQty'] = smallUnitQty
          obj['calcQty'] = calcQty
          obj['stockAvailableCalcQty'] = stockAvailableCalcQty
          obj['sumAmount'] = sumAmount
          let qty = proxy.$fn.accDiv(calcQty, obj.unitConvertCoefficient)
          let stockAvailableQty = proxy.$fn.accDiv(
            stockAvailableCalcQty,
            obj.unitConvertCoefficient
          )
          obj['qty'] = qty
          obj['stockAvailableQty'] = stockAvailableQty
          obj['details'] = row
          obj['groupConcatDepotStockIds'] = groupConcatDepotStockIds.toString()
          newArr.push(obj)
        })
        tableInfo.data = newArr
        newArr.forEach((item) => {
          tableInfo.map.set(item.key, item)
        })
      }
    }
  })
}
function getDeoptLeftCustomize() {
  //库存产品弹窗左侧配置

  let param = {
    tableKey:
      'useApplicationOrderRatifyModifyBatchNumber-com.slip.spd.entity.vo.stock.DepotStockVO',
  }
  getCustomizeSetting(param).then((res) => {
    if (res && res.success) {
      let data = res.data
      let arr = []
      let obj = {}
      if (tableInfo.isSysGroup) {
        for (let key in data.detail) {
          if (data.detail[key].sysGroupLevel > 0) {
            arr.push({
              columnName: data.detail[key].columnName,
              asTbName: data.detail[key].asTbName,
              key: key,
            })
            obj[key] = {
              queryType: 'EQUALS',
              queryCategory: 'AND',
              ignoreEmptyValue: false,
              value: null,
            }
          }
        }
      } else {
        arr.push({
          columnName: data.detail.id.columnName,
          asTbName: data.detail.id.asTbName,
          key: 'depotStockId',
        })
        obj['depotStockId'] = {
          queryType: 'EQUALS',
          queryCategory: 'AND',
          value: null,
        }
      }
      scanInfo.query.customizeUserVO = data
      individualInfo.selectObj = obj
      tableInfo.sysGroup = arr
      if (props.id) {
        getMain()
      } else {
        setBusinessDate()
      }
    }
  })
}
function getInvdividualRightCustomize() {
  //获取个体弹窗右边配置;
  let param = {
    tableKey:
      'useApplicationOrderRatifyModifySingle-com.slip.spd.entity.vo.stock.DepotStockVO',
  }
  getCustomizeSetting(param).then((res) => {
    if (res && res.success) {
      individualInfo.rightVo = res.data
    }
  })
}
async function onCallBackScanData(data, callback) {
  //扫码回调
  let { mergeDetail, detail } = data
  let productIds = applicationDetailProductIds.value
  if (productIds.indexOf(detail.productId) == -1) {
    proxy.$message({
      duration: 3500,
      type: 'warning',
      showClose: true,
      message: '请扫描申请的产品！',
    })
    return
  }

  if (tableInfo.data && tableInfo.data.length) {
    let items = tableInfo.data.filter((row) => {
      if (detail.codeType === 2 || detail.codeType === 3) {
        let arr = proxy.$fn.splitArr(row.groupConcatDepotStockIds)
        let bool = arr.includes(detail.depotStockId.toString())
        return bool
      } else if (detail.codeType === 1 || detail.codeType === 4) {
        if (row.id === mergeDetail[0].id) {
          let num = proxy.$fn.Subtr(row.stockAvailableCalcQty, row.calcQty)
          if (num <= 1) {
            return row.calcQty === row.stockAvailableCalcQty
          }
        }
      }
    })
    if (items.length) {
      callback(true)
      return
    } else {
      callback(false)
    }
  }
  mergeDetail[0].details = [detail]
  let map = await proxy.$fn.getDepotStorage(
    mergeDetail,
    tableInfo.sysGroup,
    tableInfo.map,
    otherExportOrderDetailsCustomizeListAll,
    props.id,
    individualInfo.rightVo
  )
  let flag = true
  //扫码的产品的可出库数量小于等于0的时候，将不再添加到列表中
  tableData.value.map((el) => {
    map.forEach((e2) => {
      if (el.productId === e2.productId) {
        if (el.qty <= el.preExportQty) {
          flag = false
          proxy.$message({
            duration: 3500,
            type: 'warning',
            showClose: true,
            message: '当前扫码产品的可出库数量为零！',
          })
        }
      }
    })
  })
  if (flag) {
    tableInfo.map = map
    tableInfo.data = [...map.values()]
    //根据产品id来给扫码的产品赋值申领数量
    tableInfo.data.map((item) => {
      tableData.value.map((el) => {
        if (item.productId === el.productId) {
          item.applicationQty = el.qty
          item.availableQty = proxy.$fn.Subtr(el.qty, el.preExportQty)
        }
      })
    })
  }
}
//导出excel
function exportExcel() {
  exportUseApplication(infoList.data.id).then((resp) => {
    if (resp) {
      proxy.$fn.parseExcel(resp)
    }
  })
}
//打印
function print() {
  printUseApplication(infoList.data.id).then((resp) => {
    if (resp && resp.success) {
      proxy.$print.printOrder(resp.data)
    }
  })
}
</script>

<style scoped></style>
